package com.fable.sgms.user.api.controller;

import com.fable.common.annotation.SaveSysLog;
import com.fable.common.utils.IPUtils;
import com.fable.common.utils.R;
import com.fable.common.utils.ShiroUtils;
import com.fable.sgms.syslog.dao.entity.SysLog;
import com.fable.sgms.syslog.service.SysLogService;
import com.fable.sgms.user.dao.entity.SysUser;
import io.swagger.annotations.Api;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@Api("登录接口")
public class LoginController {

    @Autowired
    private SysLogService sysLogService;

    @PostMapping(value = "/login")
    public R login(@RequestBody SysUser sysUser) {

        //记录登录日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getPassword());
            subject.login(token);
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {


            e.printStackTrace();
            return R.error(e.getMessage());
        } catch (AuthenticationException e) {

            e.printStackTrace();
            return R.error("账户验证失败");
        }

        SysLog sysLog = SysLog.builder().

                method("login").
                ip(IPUtils.getIpAddr(request)).
                username(sysUser.getUserName()).
                operation("登录").resultStatus(1).
                params(sysUser.getUserName()).
                url("/login").build();
        sysLog.setCreateTime(new Date());
        sysLogService.save(sysLog);

        return R.ok("登录成功");
    }


    /**
     * 退出
     */
    @SaveSysLog("退出")
    @GetMapping(value = "/logout")
    public R logout() {
        ShiroUtils.logout();
        return R.ok("退出成功");
    }
}
